package cn.wolfcode.car.business.web.controller.bpmnInfo;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.query.BpmnQuery;
import cn.wolfcode.car.business.service.BpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.util.StringUtils;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.common.web.AjaxResult;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @Author WaveHi
 * @Date 17/11/2021 上午 10:46
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
@Controller
@RequestMapping("/business/bpmnInfo")
public class BpmnInfoControlller {

    private final String prefix = "/business/bpmnInfo/";

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private BpmnInfoService bpmnInfoService;

    @RequiresPermissions("business:bpmnInfo:view")
    @RequestMapping("/listPage")
    public String listPage() {
        return prefix + "list";
    }

    @RequiresPermissions("business:bpmnInfo:list")
    @RequestMapping("/query")
    @ResponseBody
    public TablePageInfo<BpmnInfo> query(
            @RequestParam(value = "pageNo",required = false) Integer pageNo,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            BpmnQuery bpmnQuery) {
        System.out.println(pageNo);
        System.out.println(pageSize);
        //Judge data
        pageNo = pageNo != null ? pageNo : 1;
        pageSize = pageSize != null ? pageSize : 3;
        //Correct data
        //Query
        return bpmnInfoService.getPartOfBpmnInfos(bpmnQuery);
    }

    @RequiresPermissions("business:bpmnInfo:deployPage")
    @RequestMapping("/deployPage")
    public String deployPage() {
        return prefix + "deploy";
    }

    @RequiresPermissions("business:bpmnInfo:upload")
    @RequestMapping("/upload")
    @ResponseBody
    public AjaxResult upload(MultipartFile file) {
        if(file != null && !file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            if("bpmn".equalsIgnoreCase(extension)) {
                String upload = null;
                try {
                    upload = FileUploadUtils.upload(SystemConfig.getUploadPath(), file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(upload);
                return AjaxResult.success("上传成功", upload);
            }else {
                return  AjaxResult.error("需要上传.bpmn为后缀的文件。");
            }
        }
        return AjaxResult.error("上传失败！");
    }

    @RequiresPermissions("business:bpmnInfo:deploy")
    @RequestMapping("/deploy")
    @ResponseBody
    public AjaxResult deploy(
            @RequestParam(value = "path", required = false) String bpmnInfoPath,
            @RequestParam(value = "bpmnType", required = false) String bpmnType,
            @RequestParam(value = "info", required = false) String info) throws FileNotFoundException {
        //Judge data
        boolean bipEmpty = StringUtils.isEmpty(bpmnInfoPath);
        boolean btEmpty = StringUtils.isEmpty(bpmnType);
        boolean iEmpty = StringUtils.isEmpty(info);
        if(!bipEmpty && !btEmpty) {
            //Correct data
            bpmnInfoPath = bpmnInfoPath.trim();
            bpmnType = bpmnType.trim();
            if(!iEmpty) {
                info = info.trim();
            }
            //Deploy
            Deployment deploy = null;
            deploy = repositoryService.createDeployment()
                    .addInputStream(bpmnInfoPath,new FileInputStream(new File(SystemConfig.getProfile(),bpmnInfoPath)))
                    .deploy();
            System.out.println(deploy.getId());
            //Save data
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .deploymentId(deploy.getId())
                    .singleResult();
            if(processDefinition != null) {
                BpmnInfo bpmnInfo = new BpmnInfo();
                bpmnInfo.setBpmnType(bpmnType);
                bpmnInfo.setDeploymentId(deploy.getId());
                bpmnInfo.setDeployTime(new Date());
                bpmnInfo.setInfo(info);
                bpmnInfo.setActProcessKey(processDefinition.getKey());
                bpmnInfo.setActProcessId(processDefinition.getId());
                bpmnInfo.setBpmnName(processDefinition.getName());
                bpmnInfoService.add(bpmnInfo);
                return AjaxResult.success();
            }
            return AjaxResult.error("流程定义保存失败");
        }
        return AjaxResult.error();
    }

    @RequiresPermissions("business:bpmnInfo:readResource")
    @RequestMapping("/readResource")
    @ResponseBody
    public void readResource(
            @RequestParam(value = "deploymentId", required = false) String deploymentId,
            @RequestParam(value = "type", required = false) String type,
            HttpServletResponse response) {
        //Judge data
        boolean dIEmpty = StringUtils.isEmpty(deploymentId);
        boolean tEmpty = StringUtils.isEmpty(type);
        if(!dIEmpty && !tEmpty) {
            //Correct data
            deploymentId = deploymentId.trim();
            type = type.trim();
            //QUeryd data
            InputStream inputStream = bpmnInfoService.getResources(deploymentId, type);
            try {
                IOUtils.copy(inputStream, response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequiresPermissions("business:bpmnInfo:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(Long id){
        if(id != null) {
            bpmnInfoService.delete(id);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

}
